<template>
  <div>
    <div class="treeBox">
      数量: <span class="red">{{ orderCount }}</span> 库存成本: <span class="red">{{ profit }}</span>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 创建卡种</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
            >批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <!-- <super-query :config="superQueryConfig" @search="handleSuperQuery" /> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction
          :actions="getTableAction(record)"
          style="{ width: 400px;
          display: flex;
          flex-direction: column;
          margin:40px 0;}"
        />
      </template>
      <!-- 测试列数据 -->
      <template #isShow="{ record }">
        <a-switch v-model:checked="record.isShow" @change="handleEdit(record)" />
        <a-input v-model:value="record.sort" size="small" style="width: 120px; margin-top: 10px" @pressEnter="handleEdit(record)" />
      </template>
      <!-- 自动发货-开关 -->
      <template #keyword="{ record }">
        <div class="disC">
          <div style="width: 100px">商品编码：</div>
          <a-switch v-model:checked="record.isCode" :checkedValue="1" :unCheckedValue="0" @change="handleEditB(record)" />
        </div>
        <div class="disC" style="margin-top: 10px">
          <div style="width: 100px">关键词：</div>
          <a-switch v-model:checked="record.isMatch" :checkedValue="1" :unCheckedValue="0" @change="handleEditB(record)" />
        </div>
        <a-input v-model:value="record.keyword" size="small" style="width: 120px; margin-top: 10px" @pressEnter="handleEditB(record)" />
      </template>
      <template #ID="{ record }">
        <div @click="copy(record.id)" class="cur">{{ record.id }}</div>
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
        <template v-if="column.dataIndex === 'stores'">
          <!--富文本件字段回显插槽-->
          <div v-html="text"></div>
        </template>
        <template v-if="column.dataIndex === 'remarks'">
          <!--富文本件字段回显插槽-->
          <div v-html="text"></div>
        </template>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <CardTypModal @register="registerModal" @success="handleSuccess" :width="1100" :height="600" :bodyStyle="{ padding: '30px' }"></CardTypModal>
    <CardTypModal2 @register="registerModal2" @success="handleSuccess" :width="1100" :height="300" :bodyStyle="{ padding: '30px' }"></CardTypModal2>
  </div>
</template>

<script lang="ts" name="card-cardTyp" setup>
  import { ref, reactive, computed, unref, defineComponent } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { JAreaSelect } from '/@/components/Form';
  const pop = ref('');
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import CardTypModal from './components/CardTypModal.vue';
  import CardTypModal2 from './components/CardTypModal2.vue';
  import { columns, searchFormSchema, superQuerySchema } from './CardTyp.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, edit, createUser, selectCount } from './CardTyp.api';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useRouter } from 'vue-router';
  const { createMessage } = useMessage();
  const router = useRouter();
  const queryParam = reactive<any>({});
  const orderCount = ref('');
  const profit = ref('');
  //注册model
  const [registerModal, { openModal }] = useModal();
  //注册model
  const [registerModal2, { openModal: openModal2 }] = useModal();

  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '卡种',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [['createTime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
      },
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '卡种',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;

  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }

  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    // console.log('record id', record.id);
    router.push({ path: '/card/cardList', query: { id: record.id } });
  }
  function copy(id) {
    try {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(id);
        createMessage.success('复制成功');
      }
    } catch (error) {
      // console.log(error);
      createMessage.error('复制失败');
    }
  }
  /**
   * 编辑
   */
  function handleEditA(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  selectCount({}).then((res) => {
    orderCount.value = res.orderCount;
    profit.value = res.profit;
  });

  /**
   * 克隆
   */
  function handleCopy(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
      isCopy: true,
    });
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  // 更新排序和显隐
  async function handleEdit(record) {
    await edit({ id: record.id, sort: record.sort, isShow: record.isShow }, handleSuccess);
  }

  async function handleEditB(record) {
    await edit({ id: record.id, isMatch: record.isMatch ? 1 : 0, keyword: record.keyword, isCode: record.isCode }, handleSuccess);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  function copyOrderId(record) {
    openModal2(true, {
      record,
      isUpdate: true,
      showFooter: true,
      isCopy: true,
    });
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEditA.bind(null, record),
      },
      {
        label: '克隆',
        onClick: handleCopy.bind(null, record),
      },
      {
        label: '查看卡密',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '创建会员',
        onClick: copyOrderId.bind(null, record),
        ifShow: (_action) => {
          return record.cardStyleId === '1901810798635651073' ? true : false;
        },
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        // auth: 'card:app_card_typ:delete',
      },
    ];
  }
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
  .treeBox {
    margin: 10px;
    background: #fff;
    padding: 20px;
    box-sizing: border-box;
    .red {
      color: red;
    }
  }
  .cur {
    cursor: pointer;
    color: #1890ff;
  }
  .disC {
    display: flex;
    align-items: center;
  }
</style>
